/**
 * 1. 实现jsx dom渲染 createELement函数
 */

// 添加html元素
class ElementWrapper {
  constructor(tag) {
    this.root = document.createElement(tag);
  }

  setAttribute(name, value) {
    this.root.setAttribute(name, value);
  }

  appendChild(component) {
    this.root.appendChild(component.root);
  }
}

// 添加文本节点
class TextWrapper {
  constructor(content) {
    this.root = document.createTextNode(content);
  }
}

// 添加组件
export class Component {
  constructor() {
    // 初始化属性
    this.props = Object.create(null);
    this.children = [];
    this._root = null;
  }

  setAttribute(name, value) {
    this.props[name] = value;
  }

  appendChild(component) {
    this.children.push(component);
  }
  get root() {
    if (!this._root) {
      this._root = this.render().root;
    }
    return this._root;
  }
}

// 创建dom节点
export function createElement(tag, attrbutes, ...children) {
  let e = null;
  if (typeof tag === "string") {
    e = new ElementWrapper(tag);
  } else {
    e = new tag();
  }

  for (let p in attrbutes) {
    e.setAttribute(p, attrbutes[p]);
  }
  let insertChildren = (children) => {
    for (let child of children) {
      if (typeof child === "string") {
        child = new TextWrapper(child);
      }
      if (typeof child === "object" && child instanceof Array) {
        insertChildren(child);
      } else {
        e.appendChild(child);
      }
    }
  };
  insertChildren(children);

  return e;
}

export function render(component, parentElement) {
  parentElement.appendChild(component.root);
}
